import { reactive, watch, computed } from 'vue';

/**
 * @description useForm
 * @param opts
 *
 */
export const useForm = (opts: any) => {
  const { model, getParams, onSubmit: onSubmitHandler } = opts;
  const state: any = reactive({
    model: {},
    mode: 0, // 额外定义数据（可作为额外的特殊字段使用）： 0 新增， 1 编辑， 2查看
    data: null // 额外定义数据（根据实际业务使用）
  });

  let formModelJSONString = JSON.stringify({});
  const setModel = (model: any) => {
    formModelJSONString = JSON.stringify(model || {});
    resetModel();
  };
  const resetModel = () => {
    state.model = JSON.parse(formModelJSONString);
  };
  setModel(model);

  const onSubmit = async () => {
    let params = state.model;
    if (typeof getParams === 'function') {
      params = getParams(state.model);
    }
    if (typeof onSubmitHandler === 'function') {
      return await onSubmitHandler(params ? { ...params } : {}, state.mode, state.data);
    }
  };
  const onReset = () => {
    resetModel();
  };
  return { state, onSubmit, onReset, setModel, resetModel };
};

/**
 * @description useFormModal 弹框
 * @param opts
 *
 */
export const useFormModal = (opts: any) => {
  const { formRef, rules, onShow: onShowHandler, onCancel: onCancelHandler, ...options } = opts;
  const { state, onSubmit: onFormSubmit, resetModel: formResetModel } = useForm(options);
  state.contentLoading = false;
  state.loading = false;
  state.visible = false;

  const onSubmit = async () => {
    if (formRef?.value?.validate) {
      await formRef.value.validate();
    }
    state.loading = true;
    try {
      const res = await onFormSubmit() || {};
      if (!res.err) {
        state.visible = false;
      }
    } finally {
      state.loading = false;
    }
  };
  const onCancel = async () => {
    let res: any = { err: false };
    if (typeof onCancelHandler === 'function') {
      res = await onCancelHandler() || {};
    }
    !res.err && hide();
  };

  const show = (mode = 0, data?: any) => {
    if (typeof onShowHandler === 'function') {
      onShowHandler(mode, data);
      state.mode = mode;
      state.data = data;
      state.visible = true;
    } else {
      state.mode = mode;
      state.data = data;
      state.visible = true;
    }
  };
  const hide = () => {
    state.visible = false;
  };

  const setModel = (model: any) => {
    state.model = model || {};
    if (formRef?.value?.clearValidate) {
      formRef.value.clearValidate();
    }
  };
  const resetModel = () => {
    formResetModel();
    if (formRef?.value?.clearValidate) {
      formRef.value.clearValidate();
    }
  };

  watch(
    () => state.visible,
    (n: boolean) => {
      if (!n) {
        resetModel();
      }
    }
  );

  // k-form-modal 消费 state
  const formModalState = computed(() => {
    const obj: any = {
      'model-value': state.visible,
      loading: state.loading,
      contentLoading: state.contentLoading,
      model: state.model
    };

    if (rules) {
      obj.rules = rules;
    }

    return obj;
  });

  // k-form-modal 消费 event
  const formModalEvent = {
    'update:model-value': (val: boolean) => state.visible = val,
    submit: onSubmit,
    cancel: onCancel
  };

  return { state, formModalState, formModalEvent, onSubmit, onCancel, setModel, resetModel, show, hide };
};
